﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace TodoListWebApi.Extensions
{

    public static class JsonConvertExt
    {
        public static JsonSerializerOptions UseGlobal(this JsonSerializerOptions options)
        {
            // 中文不转义
            options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;

            // 使用camelCase命名策略
            options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

            // 忽略空值
            options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;

            // 日期格式化
            options.Converters.Add(new DateTimeConverter());

            // 枚举转字符串
            options.Converters.Add(new JsonStringEnumConverter());

            // 处理循环引用
            options.ReferenceHandler = ReferenceHandler.IgnoreCycles;

            //options.WriteIndented = false; // 生产环境通常设为false

            return options; 
        }

    }

    // 自定义日期转换器
    public class DateTimeConverter : JsonConverter<DateTime>
    {
        private const string Format = "yyyy-MM-dd HH:mm:ss";

        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return reader.TokenType == JsonTokenType.String
                ? DateTime.Parse(reader.GetString()!)
                : reader.GetDateTime();
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(Format));
        }
    }
}
